package data.operation;

import java.io.*;
import java.util.ArrayList;
import data.ListInterIterator;

public class FileOperation {
	private File file;
	
	public FileOperation(String s){
		file=new File(s);
	}
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public ListInterIterator readFile(){
		ArrayList ojs=new ArrayList();
			try {
				ObjectInputStream input=new ObjectInputStream(new FileInputStream(file));
				Object temp=input.readObject();
				while(temp!=null) {
					ojs.add(temp);
					temp=input.readObject();
				}
			input.close();
			} 
			catch (FileNotFoundException e) {e.printStackTrace();} 
			catch (IOException e) {}
			catch (ClassNotFoundException e) {}
			return new ListInterIterator<Object>(ojs);		
	}
	
	
	public void newWriteFile(ListInterIterator listInterIterator) throws  IOException{
		ArrayList ojs=listInterIterator.toArray();
		ObjectOutputStream output=new ObjectOutputStream(new FileOutputStream(file));
		for(int i=0;i<ojs.size();i++){
			output.writeObject(ojs.get(i));
		}

	}
	public void newfile() throws IOException{
		ObjectOutputStream output=new ObjectOutputStream(new FileOutputStream(file));
		output.writeObject(null);
	}
	
	public void addFile(File newfile){
		ArrayList ojs=new ArrayList();
		Object temp=null;
		try {
			ObjectInputStream input=new ObjectInputStream(new FileInputStream(file));
			temp=input.readObject();
			while(temp!=null) {
				ojs.add(temp);
				temp=input.readObject();
			}
		input.close();
		}
		catch (FileNotFoundException e) {e.printStackTrace();} 
		catch (IOException e) {}
		catch (ClassNotFoundException e) {}
		ArrayList ojstemp=new ArrayList();
		try {
			ObjectInputStream inputtemp=new ObjectInputStream(new FileInputStream(newfile));
		    temp=inputtemp.readObject();
			while(temp!=null) {
				ojstemp.add(temp);
				temp=inputtemp.readObject();
			}
		inputtemp.close();
		}
		catch (FileNotFoundException e) {e.printStackTrace();} 
		catch (IOException e) {}
		catch (ClassNotFoundException e) {}
		
		for(int i=0;i<ojstemp.size();i++){
			ojs.add(ojstemp.get(i));
		}
		ObjectOutputStream output = null;
		try {
			output = new ObjectOutputStream(new FileOutputStream(file));
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		for(int i=0;i<ojs.size();i++){
			try {
				output.writeObject(ojs.get(i));
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
		
}
